// src/api/exam/exam.ts
import request from '@/utils/request'

// -------------------- 类型定义（可按后端实际调整） --------------------
export interface ExamPaper {
  id: number
  name: string
  description: string
  durationMinutes?: number
  totalScore?: number
  passScore?: number
  randomizeQuestions?: number
  randomizeOptions?: number
  startTime?: string
  endTime?: string
}

export interface AttemptStartDTO {
  userId: number
  deviceInfo?: string
}

export interface AnswerSubmitDTO {
  timeSpentSeconds: number
  answers: Array<
    | { questionId: number; selectedOptionKeys: string[] }
    | { questionId: number; booleanAnswer: boolean }
    | { questionId: number; fillAnswers: string[] }
  >
}

export interface MyAttemptsParams {
  userId: number
  page?: number
  size?: number
}

export interface WrongBookParams {
  userId: number
  tagId?: number
}

export interface PracticeParams extends WrongBookParams {
  limit?: number
}

// 试卷-题目项（批量添加）
export interface PaperQuestionItemDTO {
  questionId: number
  sortOrder?: number
  score?: number
  required?: number
  scoringConfigJson?: string
}

// 题目与选项（精简定义，用于管理端）
export interface ExamQuestionOption {
  optionKey: string
  content: string
  isCorrect?: number
}

export interface ExamQuestion {
  id?: number
  questionType: number // 1:单选 2:多选 3:判断 4:填空
  stem: string
  analysis?: string
  difficulty?: number
  score?: number
  options?: ExamQuestionOption[]
  tagIds?: number[]
}

export interface PageParams {
  keyword?: string
  page?: number
  size?: number
  [key: string]: any
}

// -------------------- 试卷-题目关联（PaperQuestion） --------------------
export interface ExamPaperQuestion {
  id?: number
  paperId: number
  questionId: number
  sortOrder?: number
  score?: number
  scoringConfigJson?: string
  required?: number // 1-必答；0-非必答
}

// -------------------- API 方法 --------------------

/** 可参加考试列表 */
export function getAvailableExams(): Promise<any> {
  return request({
    url: '/api/exams/available',
    method: 'get',
  })
}

/** 开始考试（创建 attempt） */
export function startExam(paperId: number | string, data: AttemptStartDTO): Promise<any> {
  return request({
    url: `/api/exams/${paperId}/start`,
    method: 'post',
    data,
  })
}

/** 提交答案（自动评分） */
export function submitAnswers(attemptId: number | string, data: AnswerSubmitDTO): Promise<any> {
  return request({
    url: `/api/exams/${attemptId}/submit`,
    method: 'post',
    data,
  })
}

/** 我的历史考试 */
export function getMyAttempts(params: MyAttemptsParams): Promise<any> {
  return request({
    url: '/api/exams/attempts',
    method: 'get',
    params,
  })
}

/** 历史考试记录（包含试卷与用户信息，支持分页） */
export function pageUserAttempts(params: { page?: number; size?: number; keyword?: string; userId?: number; status?: number }): Promise<any> {
  return request({
    url: '/api/exams/userAttempts',
    method: 'get',
    params,
  })
}

/** 考试详情（含答案） */
export function getAttemptDetail(id: number | string): Promise<any> {
  return request({
    url: `/api/exams/attempts/${id}`,
    method: 'get',
  })
}

/** 我的错题本 */
export function getWrongBook(params: WrongBookParams): Promise<any> {
  return request({
    url: '/api/wrong-book',
    method: 'get',
    params,
  })
}

/** 错题练习 */
export function practiceWrongBook(params: PracticeParams): Promise<any> {
  return request({
    url: '/api/wrong-book/practice',
    method: 'get',
    params,
  })
}

// -------------------- 试卷管理 --------------------

/** 试卷分页/列表（使用请求体传参 {page,size}；适配返回 {list,total,pageNum/page,pageSize/size}） */
export function pagePapers(
  params: PageParams & { page?: number; size?: number; pageNum?: number; pageSize?: number },
): Promise<any> {
  const { page, size, pageNum, pageSize, ...rest } = params || {}
  const finalBody = {
    ...rest,
    page: page ?? pageNum ?? 1,
    size: size ?? pageSize ?? 10,
  }
  return request({
    url: '/api/papers/pageDetail',
    method: 'post',
    data: finalBody,
  })
}

/** 创建试卷 */
export function createPaper(data: Partial<ExamPaper>): Promise<any> {
  return request({
    url: '/api/papers',
    method: 'post',
    data,
  })
}

/** 更新试卷 */
export function updatePaper(id: number | string, data: Partial<ExamPaper>): Promise<any> {
  return request({
    url: `/api/papers/${id}`,
    method: 'put',
    data,
  })
}

/** 删除试卷（REST 约定，若后端未实现请忽略） */
export function deletePaper(id: number | string): Promise<any> {
  return request({
    url: `/api/papers/${id}`,
    method: 'delete',
  })
}

/** 试卷详情 */
export function getPaperDetail(id: number | string): Promise<any> {
  return request({
    url: `/api/papers/${id}`,
    method: 'get',
  })
}

/** 批量向试卷添加试题 */
export function addPaperQuestions(
  paperId: number | string,
  data: PaperQuestionItemDTO[],
): Promise<any> {
  return request({
    url: `/api/papers/${paperId}/questions`,
    method: 'post',
    data,
  })
}

/** 创建试卷-题目关联 */
export function createPaperQuestion(data: ExamPaperQuestion): Promise<any> {
  return request({
    url: '/api/paper-questions',
    method: 'post',
    data,
  })
}

/** 更新试卷-题目关联（按主键） */
export function updatePaperQuestion(id: number | string, data: Partial<ExamPaperQuestion>): Promise<any> {
  return request({
    url: `/api/paper-questions/${id}`,
    method: 'put',
    data,
  })
}

/** 删除试卷-题目关联（按主键） */
export function deletePaperQuestion(id: number | string): Promise<any> {
  return request({
    url: `/api/paper-questions/${id}`,
    method: 'delete',
  })
}

/** 查询试卷-题目关联详情（按主键） */
export function getPaperQuestionDetail(id: number | string): Promise<any> {
  return request({
    url: `/api/paper-questions/${id}`,
    method: 'get',
  })
}

/** 按试卷ID列出关联项 */
export function listPaperQuestionsByPaper(paperId: number | string): Promise<any> {
  return request({
    url: `/api/paper-questions/byPaper/${paperId}`,
    method: 'get',
  })
}

/** 删除指定试卷下某题目的关联（复合键） */
export function deletePaperQuestionByPaper(paperId: number | string, questionId: number | string): Promise<any> {
  return request({
    url: `/api/paper-questions/byPaper/${paperId}/${questionId}`,
    method: 'delete',
  })
}

// -------------------- 题库管理 --------------------

/** 题目分页查询 */
export function pageQuestions(
  params: PageParams & { questionType?: number; difficulty?: number; tagId?: number },
): Promise<any> {
  return request({
    url: '/api/questions',
    method: 'get',
    params,
  })
}

/** 创建题目 */
export function createQuestion(data: ExamQuestion): Promise<any> {
  return request({
    url: '/api/questions',
    method: 'post',
    data,
  })
}

/** 更新题目 */
export function updateQuestion(id: number | string, data: Partial<ExamQuestion>): Promise<any> {
  return request({
    url: `/api/questions/${id}`,
    method: 'put',
    data,
  })
}

/** 删除题目 */
export function deleteQuestion(id: number | string): Promise<any> {
  return request({
    url: `/api/questions/${id}`,
    method: 'delete',
  })
}

/** 题目详情 */
export function getQuestionDetail(id: number | string): Promise<any> {
  return request({
    url: `/api/questions/${id}`,
    method: 'get',
  })
}
